class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        int n = nums.size();
        vector<int> idx(n);
        for(int i = 0; i < n; i++) idx[i] = i;
        sort(idx.begin(), idx.end(), [&](int i, int j)->bool{
            if(nums[i] != nums[j]) return nums[i] < nums[j];
            return i < j;
        });
        for(int i = 0; i < n - 1; i++){
            if(nums[idx[i + 1]] == nums[idx[i]]){
                if(idx[i + 1] - idx[i] <= k) return true;
            }
        }
        return false;
    }
};